from django.db import models

# Things needed from NoPBX
from nopbx.core.models import BaseModule
#from nopbx.modules.infrastructure.models import Location
from nopbx.schedule.models import Calendar

"""
Context Lookup Table
"""
class ContextManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(name = name)

class Context(BaseModule):
    """
    Logical seperation of 'things'
    """
    CONTEXT_TYPE_CHOICES = (
        (1, 'Extension'),
        (2, 'Device'),
        (3, 'Operator'),
    )

    name         = models.CharField(max_length = 50, unique = True)
    context_type = models.PositiveSmallIntegerField(default = '1', choices = CONTEXT_TYPE_CHOICES)

    objects = ContextManager()
    class Meta:
        ordering = ['name']

    # Functions
    def __unicode__(self):
        return self.name

    def natural_key(self):
        return self.name



"""
Extensions
"""
class ExtensionManager(models.Manager):
    def get_by_natural_key(self, extension, context):
        return self.get(extension = extension, context = Context.objects.get_by_natural_key(context))

class Extension(BaseModule):
    extension   = models.CharField(max_length = 50)
    context     = models.ForeignKey(Context, limit_choices_to = {'context_type':1})

    calendars   = models.ManyToManyField(Calendar, blank = True, null = True)

    objects = ExtensionManager()
    class Meta:
        ordering = ['context', 'extension']
        unique_together = ('extension', 'context')

    # Functions
    def __unicode__(self):
        return '%s@%s' % (self.extension, self.context)

    def natural_key(self):
        return (self.extension, self.context)

